//
//  HTTPClient.swift
//  SinaWeiBo20
//
//  Created by tarena on 16/3/25.
//  Copyright © 2016年 tarena. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethod: String {
    case GET = "GET"
    case POST = "POST"
}

//一般网络访问的工具类需要 设计成单例
class HTTPClient: AFHTTPSessionManager {
    
    //定义反转域名
    let domain = "com.baidu.data.error"
    
    static let sharedClient: HTTPClient = {
        let urlString = "https://api.weibo.com/"
        let url = NSURL(string: urlString)
        let tools = HTTPClient(baseURL: url)
        
        //支持解析的数据类型
         tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        
    }()
    
    
    //网络请求方法的封装 GET + Post
    func requestJSONDict(method: HTTPMethod, urlString: String,parameters:[String : AnyObject]?, finished: (dict:[String: AnyObject]?,error:NSError?)->()) {
        if method == .GET {
            //get请求
            GET(urlString, parameters: parameters, progress: nil, success: { (_ , result) -> Void in
                guard let dict = result as? [String : AnyObject] else {
                    //获取的数据不能转换为字典类型数据
                    //执行失败的回调
                    //自定义错误信息
                    let myError = NSError(domain: self.domain, code: 10000, userInfo: [NSLocalizedDescriptionKey : "数据结构出错"])
                    finished(dict: nil, error: myError)
                    return
                }
                
                //执行成功的回执
                finished(dict: dict, error: nil)
                
                }, failure: { (_ , error ) -> Void in
                    finished(dict: nil, error: error)
                   
            })
        }else {
            //  post 请求
            //POST请求
            POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                guard let dict = result as? [String : AnyObject] else {
                    //获取的数据不能够转换为字典类型数据
                    //执行失败的回调
                    //自定义错误信息
                    //domain: 域名的反转信息 cn.itcast
                    //自定义错误码 一般为 负数  或者 大于10000
                    let myError = NSError(domain: self.domain, code: 10000, userInfo: [NSLocalizedDescriptionKey : "数据结构出错"])
                    finished(dict: nil, error: myError)
                    return
                    
                }
                
                
                //执行成功的回调
                finished(dict: dict, error: nil)
                }, failure: { (_, error) -> Void in
                    finished(dict: nil, error: error)
                    printLog(error)
            })

        }
        
        
    }
    
}
